package day01;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author feng
 * @Date 2021/10/13 20:47
 * Lock锁:解决线程安全的第三种方式
 * 手动添加释放
 */
public class LockTest implements Runnable {
    private int ticket = 100;
    private ReentrantLock reentrantLock = new ReentrantLock(true); //公平锁

    @Override
    public void run() {

        while (true) {
            //手动上锁
            reentrantLock.lock();
            try {
                if (ticket > 0) {
                    Thread.sleep(100);
                    System.out.println(Thread.currentThread().getName() + "售出第" + ticket + "张票");
                    ticket--;
                }else {
                    break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
             reentrantLock.unlock();
            }

        }

    }

    public static void main(String[] args) {
        LockTest lockTest = new LockTest();
        Thread t1 = new Thread(lockTest);
        Thread t2 = new Thread(lockTest);
        Thread t3 = new Thread(lockTest);
        t1.setName("t1");
        t2.setName("t2");
        t3.setName("t3");
        t1.start();
        t2.start();
        t3.start();
    }
}
